import random
import uuid
import datetime
from io import BytesIO

from django.http import JsonResponse
from django.shortcuts import render, HttpResponse, redirect
from django.conf import settings
from django.db.models import Q
from utils.tencent.sms import send_sms_single
from web1 import models
from web1.forms.account import RegisterModelForm, SendSmsForm, LoginSMSForm, LoginForm


def register(request):
    """ 注册 """
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})
    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        # 校验通过,保存数据
        instance = form.save()  # 会保存有定义的字段，舍弃没有定义的字段，并返回最后保存的这条记录对象，instance=form.save()

        # 创建交易记录
        # 方式一
        policy_object = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
        models.Transaction.objects.create(
            status=2,
            order=str(uuid.uuid4()),
            user=instance,
            price_policy=policy_object,
            count=0,
            price=0,
            start_datetime=datetime.datetime.now()
        )

        # 方式二

        return JsonResponse({'status': True, 'data': '/login/'})   # 注册成功让其跳转到登录
    return JsonResponse({'status': False, 'error': form.errors})   # 注册失败返回错误信息


def send_sms(request):
    """"发送短信"""
    # 用forms来校验,多传一个参数request给forms去校验
    form = SendSmsForm(request, data=request.GET)
    if form.is_valid():
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def login_sms(request):
    """短信登录"""
    if request.method == 'GET':
        form = LoginSMSForm()
        return render(request, 'login_sms.html', {'form': form})

    form = LoginSMSForm(data=request.POST)
    if form.is_valid():
        # 用户输入正确，登录成功，若要存入session，就要把forms返回的user_object拿到
        user_object = form.cleaned_data['mobile_phone']
        request.session['user_id'] = user_object.id
        request.session.set_expiry(60 * 60 * 24 * 14)  # 14天后过期

        return JsonResponse({'status': True, 'data': '/index/'})
    return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, 'login.html', {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        # user_object = models.UserInfo.objects.filter(username=username,password=password).first()
        # 如果邮箱和密码  或者 手机和密码 跟数据库相等
        user_object = models.UserInfo.objects.filter(Q(email=username)|Q(mobile_phone=username)).filter(password=password).first()
        if user_object:
            # 邮箱和密码  或者 手机和密码 正确
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)   # 14天后过期
            return redirect('index')
        form.add_error('username', '用户名或密码错误')

    return render(request, 'login.html', {'form': form})


def image_code(request):
    """生成图片验证码"""
    from io import BytesIO
    from utils.image_code import check_code

    image_object, code = check_code()

    # 把图片写到内存中
    stream = BytesIO()
    image_object.save(stream, 'png')
    # 把code写入session,并设置60秒之后过期(默认14天)
    request.session['image_code'] = code
    request.session.set_expiry(60)

    return HttpResponse(stream.getvalue())


def logout(request):
    request.session.flush()  # 清空session里的数据
    return redirect('index')
